﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using System.Diagnostics;

namespace NAntExt.Tasks
{
    /// <summary>
    /// The base class for all the tasks which use the schtasks.exe.
    /// </summary>
    public abstract class SchtasksTaskBase : Task
    {
        
        /// <summary>
        /// The server the task is running on. Optional. See /S argument.
        /// </summary>
        [TaskAttribute("server", Required = false)]
        [StringValidator(AllowEmpty = false)]
        public string Server { get; set; }

        /// <summary>
        /// The name of the task. See /TN argument.
        /// </summary>
        [TaskAttribute("taskName", Required = false)]
        [StringValidator(AllowEmpty = false)]
        public string TaskName { get; set; }
        
        /// <summary>
        /// Executes schtasks and get the result.
        /// </summary>
        /// <param name="arguments">The arguments for the schtasks.exe.</param>
        /// <returns>The result of the query.</returns>
        protected string ExecuteSchtasks(string arguments)
        {
            var schtasksProcess = new Process();
            schtasksProcess.StartInfo = new ProcessStartInfo("schtasks.exe", arguments)
            {
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                UseShellExecute = false,
                LoadUserProfile = true                
            };
            schtasksProcess.Start();
            schtasksProcess.WaitForExit();
            return schtasksProcess.StandardOutput.ReadToEnd();
        }
    }
}
